package com.demo.service;

import mapper.RoleBean;
import mapper.UserBean;
import mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.faces.context.FacesContext;
import java.util.ArrayList;
import java.util.List;

/**
 * User: yuebo
 * Date: 13-8-29
 * Time: 下午10:09
 */
@Service
public class UserService implements UserDetailsService {
   @Autowired
   private UserMapper userMapper;
   public static final String SESSION_KEY="USER_SESSION";

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        List<RoleBean> roles=userMapper.getUserRole(s);
        List<SimpleGrantedAuthority> grantedAuthorityList = new ArrayList<SimpleGrantedAuthority>();
        for (RoleBean role:roles){
            SimpleGrantedAuthority grantedAuthority=new SimpleGrantedAuthority(role.getRolename());
            grantedAuthorityList.add(grantedAuthority);
        }
        UserBean userBean = userMapper.getUser(s);
        if(userBean==null)
            return null;
        User user=new User(userBean.getUsername(),userBean.getPassword(), grantedAuthorityList);
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(SESSION_KEY,userBean);

        return user;
    }

    public static UserBean  getLoginUser(){
        return (UserBean) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(SESSION_KEY);
    }
}
